package com.frame.pageform.remote;

/**
 * 远程调用servlet服务
 */
import java.beans.*;
import java.io.*;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class RemoteServlet  extends HttpServlet{

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws
			ServletException, IOException
	{
		process(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws
			ServletException, IOException
	{
		process(request, response);
	}
	private void process(HttpServletRequest request,
						 HttpServletResponse response) throws ServletException, IOException
	{
		try{
			InputStream in = request.getInputStream();
			ObjectInputStream oin = new ObjectInputStream(in);
			RemoteRequest remrequest=(RemoteRequest)oin.readObject();

			String method=remrequest.getMethodName();
			Object obj=Class.forName(remrequest.getClassName()).newInstance();
			Object[] parameters = remrequest.getParameters().toArray();

			Object returnobj=execute(obj,method,parameters);

			returnObject(returnobj,response);
		}
		catch(Exception e){
			returnObject(e,response);
			e.printStackTrace();
		}
	}
	private Object execute(Object obj, String methodName, Object[] parameters) throws
			Exception
	{
		BeanInfo  beanInfo=Introspector.getBeanInfo(obj.getClass());
		Method method = null;
		MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors();
		for (int i = 0; i < methodDescriptors.length; i++) {
			MethodDescriptor descriptor = methodDescriptors[i];
			method = descriptor.getMethod();
			if (method.getName().equalsIgnoreCase(methodName))
				break;
			method=null;
		}
		if(method!=null)
			return method.invoke(obj, parameters);
		return null;
	}
	private void returnObject(Object obj, HttpServletResponse response) throws IOException{
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ObjectOutputStream oout = new ObjectOutputStream(out);
		oout.writeObject(obj);
		oout.flush();
		response.getOutputStream().write(out.toByteArray());
		response.getOutputStream().flush();
		response.getOutputStream().close();
	}
}
